package com.glq1218.domain;

import com.glq1218.constant.HttpStatus;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serial;
import java.io.Serializable;

/**
 * @author glq1218
 * @description 统一相应类
 * @since 2023/4/10 9:33
 */

@Data
@AllArgsConstructor
@NoArgsConstructor
// @Schema(description = "统一响应类")
public class R<T> implements Serializable {

    /**
     * 成功
     */
    public static final Integer SUCCESS = HttpStatus.SUCCESS;
    /**
     * 失败
     */
    public static final Integer FAIL = HttpStatus.ERROR;
    @Serial
    private static final long serialVersionUID = -5002110469085248362L;
    // @Schema(description = "状态码")
    private Integer code;
    // @Schema(description = "信息")
    private String msg;
    // @Schema(description = "数据")
    private T data;

    public static <T> R<T> ok() {
        return restR(SUCCESS, "操作成功", null);
    }

    public static <T> R<T> ok(String msg) {
        return restR(SUCCESS, msg, null);
    }

    public static <T> R<T> ok(T data) {
        return restR(SUCCESS, "操作成功", data);
    }

    public static <T> R<T> ok(String msg, T data) {
        return restR(SUCCESS, msg, data);
    }

    public static <T> R<T> fail() {
        return restR(FAIL, "操作失败", null);
    }

    public static <T> R<T> fail(String msg) {
        return restR(FAIL, msg, null);
    }

    public static <T> R<T> fail(T data) {
        return restR(FAIL, "操作失败", data);
    }

    public static <T> R<T> fail(T data, String msg) {
        return restR(FAIL, msg, data);
    }

    public static <T> R<T> fail(Integer code, String msg) {
        return restR(code, msg, null);
    }

    private static <T> R<T> restR(Integer code, String msg, T data) {
        R<T> apiR = new R<>();
        apiR.setCode(code);
        apiR.setMsg(msg);
        apiR.setData(data);
        return apiR;
    }

    public static <T> Boolean isError(R<T> ret) {
        return !isSuccess(ret);
    }

    public static <T> Boolean isSuccess(R<T> ret) {
        return R.SUCCESS.equals(ret.getCode());
    }
}
